from fastapi import APIRouter, UploadFile, File, HTTPException
from fastapi.responses import JSONResponse
from typing import Dict, Any
import os
import uuid
from pathlib import Path
import shutil
from LLM.llm import LLMClient
import logging

router = APIRouter(prefix="/api/beauty", tags=["beauty"])
logger = logging.getLogger(__name__)

# 初始化LLM客户端
llm_client = LLMClient()

# 临时图片存储目录
TEMP_DIR = Path("temp")
TEMP_DIR.mkdir(exist_ok=True)

@router.post("/analyze")
async def analyze_beauty(file: UploadFile = File(...)) -> Dict[str, Any]:
    """
    分析上传图片的颜值
    
    Args:
        file: 上传的图片文件
        
    Returns:
        包含颜值分析结果的JSON响应
    """
    if not file.content_type or not file.content_type.startswith("image/"):
        raise HTTPException(status_code=400, detail="请上传图片文件")
    
    # 生成唯一文件名
    file_extension = file.filename.split('.')[-1] if '.' in file.filename else 'jpg'
    unique_filename = f"{uuid.uuid4()}.{file_extension}"
    temp_file_path = TEMP_DIR / unique_filename
    
    try:
        # 保存上传的文件到临时目录
        with open(temp_file_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)
        
        logger.info(f"临时保存图片: {temp_file_path}")
        
        # 使用LLM分析颜值
        result = llm_client.analyze_image(
            image_path=str(temp_file_path),
            prompt="""请分析这张图片中人物的颜值，基于面部特征、五官比例、皮肤状态等维度给出评分和描述。
            请严格按照以下格式返回JSON：
            {
                "subject_type": "human",
                "confidence": "high",
                "analysis": {
                    "beauty_score": 85,
                    "gender": "female",
                    "age_range": "20-25",
                    "tags": ["清秀", "知性", "气质优雅"]
                }
            }"""
        )
        
        logger.info(f"颜值分析完成: {result}")
        
        # 返回分析结果
        return {
            "success": True,
            "data": result,
            "message": "颜值分析成功"
        }
        
    except Exception as e:
        logger.error(f"颜值分析失败: {str(e)}")
        raise HTTPException(status_code=500, detail=f"分析失败: {str(e)}")
        
    finally:
        # 删除临时文件
        try:
            if temp_file_path.exists():
                temp_file_path.unlink()
                logger.info(f"删除临时文件: {temp_file_path}")
        except Exception as e:
            logger.warning(f"删除临时文件失败: {str(e)}")

@router.get("/health")
async def health_check() -> Dict[str, str]:
    """健康检查接口"""
    return {"status": "ok", "message": "颜值检测服务正常运行"}